﻿using leaf.Base;
using leaf.Entity;
using System;
using System.IO;
using System.Text;
using System.Web.Mvc;

namespace leaf.Controllers
{
    /// <summary>
    /// 服务器验证
    /// </summary>
    public class HomeController : Controller
    {
        /// <summary>
        /// 配置微信服务器 & 开启 获取微信基本密钥 线程
        /// </summary>
        public ActionResult InitService()
        {
            //获取token公钥
            string token = BaseSupport.GetConfig("token");
            //存放请求数据
            string timestamp_wx = string.Empty;
            string nonce_wx = string.Empty;
            string echostr_wx = string.Empty;
            string signature_wx = string.Empty;
            //提取请求信息字段
            if (!string.IsNullOrEmpty(Request.Params["timestamp"]))
            {
                timestamp_wx = Request.Params["timestamp"];
            }
            if (!string.IsNullOrEmpty(Request.Params["signature"]))
            {
                signature_wx = Request.Params["signature"];
            }
            if (!string.IsNullOrEmpty(Request.Params["nonce"]))
            {
                nonce_wx = Request.Params["nonce"];
                if (!string.IsNullOrEmpty(Request.Params["echostr"]))
                {
                    echostr_wx = Request.Params["echostr"];
                }

                //字典排序
                string[] strs = { token, timestamp_wx, nonce_wx };
                Array.Sort(strs);
                //拼接-加密
                string signature_me = string.Join("", strs);
                signature_me = BaseSupport.SHA1(signature_me, Encoding.UTF8);
                //对比
                if (signature_me.Equals(signature_wx))
                {
                    //Task 后期需要把生成相应放到这里
                }
                //生成响应
                Response.Clear();
                Response.Write(echostr_wx);
                Response.End();
            }
            return View();
        }

        /// <summary>
        /// 设置公众号菜单
        /// </summary>
        public string SetWXMenu()
        {
            if (Global.GetWXBaseInfo() == null)
            {
                return "基础信息换取失败";
            }

            var uri = Global.SetWXMenuUri();
            var filePath = Path.Combine(Global.BaseDir, @"Assts\wx_menu.json");
            string menuStr = BaseSupport.GetStrForPath(filePath);
            Global.log.Info("设置微信菜单");
            var rsp = HttpSay.Post<WXErr>(uri, menuStr);
            return rsp.Errmsg;
        }
    }
}